package org.niux.AutoLoginQQ.ui;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.niux.AutoLoginQQ.VO.QQNumVO;
import org.niux.AutoLoginQQ.common.Constant;
import org.niux.AutoLoginQQ.operate.AppOperate;
import org.niux.AutoLoginQQ.timer.TimingLoginTimer;
import org.niux.AutoLoginQQ.util.ConfigurationFile;

public class ConfigDialog extends Dialog {

	private Log log = LogFactory.getLog(this.getClass());
	
	protected Object result;
	protected Shell shell;
	private Text delayTime;
	private Text topLevel;
	private Text splitStr;
	private Combo combo;
	private Text sameTimeLogin;
	private Text loginTime;
	private Combo isLoginNeedVerifyCode;
	private Button autoShutdown;
	private Button autoRun;
	private Button autoLogin;
	private Button seize;
	private Button timingLogin;
	private Combo hour;
	private Label hourLabel;
	private Combo minute;
	private Label minuteLabel;
	private Main gui;
	
	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public ConfigDialog(Shell parent, int style, Main gui) {
		super(parent, style);
		setText("设置");
		this.gui = gui;
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		
		//窗口居中
		int width = shell.getMonitor().getClientArea().width;  
		int height = shell.getMonitor().getClientArea().height;  
				
		int x = shell.getSize().x;  
		int y = shell.getSize().y; 
				
		if(x > width){  
			shell.getSize().x = width;  
		}  
				        
		if(y > height){  
			shell.getSize().y = height;  
		}  
				        
		shell.setLocation((width - x) / 2, (height - y) / 2);
				
		shell.open();
		shell.layout();
		
		InputStream is=this.getClass().getResourceAsStream("icon/ico.png");
		Image image = new Image(Display.getDefault(),is);
		shell.setImage(image);
		
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.SYSTEM_MODAL);
		shell.setBackground(SWTResourceManager.getColor(173, 216, 230));
		shell.setSize(450, 300);
		shell.setText("设置");
		
		delayTime = new Text(shell, SWT.BORDER);
		delayTime.setBounds(10, 10, 86, 25);
		delayTime.setText(Constant.DELAY_TIME);
		
		Label label = new Label(shell, SWT.NONE);
		label.setBackground(SWTResourceManager.getColor(173, 216, 230));
		label.setBounds(102, 10, 109, 25);
		label.setText("登录间隔时间（秒）");
		
		topLevel = new Text(shell, SWT.BORDER);
		topLevel.setBounds(10, 72, 86, 25);
		topLevel.setText(Constant.TOP_LEVEL);
		
		Label lblq = new Label(shell, SWT.NONE);
		lblq.setBackground(SWTResourceManager.getColor(173, 216, 230));
		lblq.setBounds(102, 72, 77, 25);
		lblq.setText("\u6302Q\u7B49\u7EA7\u4E0A\u9650");
		
		Button sava = new Button(shell, SWT.NONE);
		sava.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("static-access")
			@Override
			public void widgetSelected(SelectionEvent e) {
				Constant.DELAY_TIME = delayTime.getText();
				Constant.LOGIN_STATUS = combo.getData(combo.getText()).toString();
				Constant.TOP_LEVEL = topLevel.getText();
				Constant.SPLIT_STR = splitStr.getText();
				Constant.SAME_TIME_LOGIN = sameTimeLogin.getText();
				Constant.IS_LOGIN_NEED_VERIFYCODE = isLoginNeedVerifyCode.getData(isLoginNeedVerifyCode.getText()).toString();
				Constant.LOGIN_TIME = loginTime.getText();
				if(autoShutdown.getSelection()){
					Constant.AUTO_SHUTDOWN = true;
					
					if(!Constant.LOGIN_QUEEN.isEmpty() || !Constant.ALREADY_LOGIN_QUEEN.isEmpty()){
						Constant.SHUTDOWN = true;
					}
				} else {
					Constant.AUTO_SHUTDOWN = false;
					Constant.SHUTDOWN = false;
				}
				
				Constant.AUTO_RUN = autoRun.getSelection();
				Constant.AUTO_LOGIN = autoLogin.getSelection();
				Constant.SEIZE = seize.getSelection();
				Constant.TIMING_LOGIN = timingLogin.getSelection();
				
				Constant.HOUR = hour.getText();
				Constant.MINUTE = minute.getText();
				
				// 启动定时登录器
				if(Constant.TIMING_LOGIN){
					log.debug("启动定时登录器");
					Display.getDefault().asyncExec(new Runnable() {
						public void run() {
							log.debug("启动定时登录器");
							Calendar calendar = Calendar.getInstance();
							
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							
							log.debug("当前时间为" + sdf.format(calendar.getTime()));
							Calendar setterTime = Calendar.getInstance();

							setterTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(Constant.HOUR));
							setterTime.set(Calendar.MINUTE, Integer.parseInt(Constant.MINUTE));
							setterTime.set(Calendar.SECOND, 0);
							
							log.debug("设置的时间为" + sdf.format(setterTime.getTime()));
							

							boolean isAfterSettingTime = calendar.after(setterTime);

							// int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
							// log.debug("当前时间是：" + hourOfDay + "时");

							if (isAfterSettingTime) {// 如果当时时间超过了设置的定时登录时间，则设定定时登录器启动时间为下一天的指定时间
								log.debug("设置为下一天");
								calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
								calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(Constant.HOUR));
								calendar.set(Calendar.MINUTE, Integer.parseInt(Constant.MINUTE));
								calendar.set(Calendar.SECOND, 0);
							} else {
								log.debug("设置为当天");
								calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(Constant.HOUR));
								calendar.set(Calendar.MINUTE, Integer.parseInt(Constant.MINUTE));
								calendar.set(Calendar.SECOND, 0);
							}

							log.debug("设置定时登录器的启动时间为" + sdf.format(calendar.getTime()));

							List<QQNumVO> qqList = gui.getAllQQ();
							log.debug("有"+qqList.size()+"个QQ");
							
							Timer timer5 = new Timer();
							TimingLoginTimer timingLoginTimer = new TimingLoginTimer(gui, gui.getAllQQ());
							timer5.schedule(timingLoginTimer, calendar.getTime(), 24 * 60 * 60 * 1000);
//							
//							List<QQNumVO> qqList = gui.getAllQQ();
//							
//							Calendar calendar = Calendar.getInstance();
//							
//							int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
//							
//							if(hourOfDay > Integer.parseInt(Constant.HOUR)){//如果当时时间超过了设置的定时登录时间，则设定定时登录器启动时间为下一天的指定时间
//								calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 1);
//								calendar.set(Calendar.HOUR, Integer.parseInt(Constant.HOUR));
//								calendar.set(Calendar.MINUTE, Integer.parseInt(Constant.MINUTE));
//								calendar.set(Calendar.SECOND, 0);
//							} else {
//								calendar.set(Calendar.HOUR, Integer.parseInt(Constant.HOUR));
//								calendar.set(Calendar.MINUTE, Integer.parseInt(Constant.MINUTE));
//								calendar.set(Calendar.SECOND, 0);
//							}
//							
//							Timer timer5 = new Timer();
//							TimingLoginTimer timingLoginTimer = new TimingLoginTimer(gui,qqList);
//							timer5.schedule(timingLoginTimer, calendar.getTime(), 24 * 60 * 60 * 1000);
						}
					});
				}
				
				AppOperate appOperate = new AppOperate();
				appOperate.setAutoRun(Constant.AUTO_RUN);
				
				ConfigurationFile config = new ConfigurationFile();
				
				String file = "config.ini";
				
				try {
					config.setProfileString(file, "Config", "DelayTime", Constant.DELAY_TIME);
					config.setProfileString(file, "Config", "LoginStatus", Constant.LOGIN_STATUS+
							" ;online是在线，callme是Q我吧，away是离开，busy是忙碌，silent是请勿打扰，hidden是隐身，offline是离线");
					config.setProfileString(file, "Config", "TopLevel", Constant.TOP_LEVEL);
					config.setProfileString(file, "Config", "SplitStr", Constant.SPLIT_STR);
					config.setProfileString(file, "Config", "SameTimeLogin", Constant.SAME_TIME_LOGIN);
					config.setProfileString(file, "Config", "IsLoginNeedVerifyCode", Constant.IS_LOGIN_NEED_VERIFYCODE);
					config.setProfileString(file, "Config", "LoginTime", Constant.LOGIN_TIME);
					config.setProfileString(file, "Config", "AutoShutdown", Constant.AUTO_SHUTDOWN ? "true" : "false");
					config.setProfileString(file, "Config", "AutoRun", Constant.AUTO_RUN ? "true" : "false");
					config.setProfileString(file, "Config", "AutoLogin", Constant.AUTO_LOGIN ? "true" : "false");
					config.setProfileString(file, "Config", "Seize", Constant.SEIZE ? "true" : "false");
					config.setProfileString(file, "Config", "TimingLogin", Constant.TIMING_LOGIN ? "true" : "false");
					config.setProfileString(file, "Config", "Hour", Constant.HOUR);
					config.setProfileString(file, "Config", "Minute", Constant.MINUTE);
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
				shell.close();
			}
		});
		sava.setBounds(185, 243, 72, 22);
		sava.setText("\u4FDD\u5B58");
		
		splitStr = new Text(shell, SWT.BORDER);
		splitStr.setBounds(10, 103, 86, 25);
		splitStr.setText(Constant.SPLIT_STR);
		
		Label label_1 = new Label(shell, SWT.NONE);
		label_1.setBackground(SWTResourceManager.getColor(173, 216, 230));
		label_1.setBounds(102, 103, 54, 25);
		label_1.setText("\u5206\u5272\u5B57\u7B26");
		
		combo = new Combo(shell, SWT.NONE);
		
		combo.setItems(new String[] {"在线", "Q我吧", "离开", "忙碌", "请勿打扰", "隐身", "离线"});
		
		combo.setData("在线","online");
		combo.setData("Q我吧","callme");
		combo.setData("离开","away");
		combo.setData("忙碌", "busy");
		combo.setData("请勿打扰", "silent");
		combo.setData("隐身", "hidden");
		combo.setData("离线", "offline");

		combo.setBounds(10, 41, 86, 23);
		
		int count = combo.getItemCount();
		
		for(int i = 0; i < count; i++){
			if(combo.getData(combo.getItem(i)).toString().equals(Constant.LOGIN_STATUS)){
				combo.select(i);
				break;
			}
		}
		
		
		Label lblQq = new Label(shell, SWT.NONE);
		lblQq.setBackground(SWTResourceManager.getColor(173, 216, 230));
		lblQq.setBounds(102, 41, 77, 25);
		lblQq.setText("QQ登录状态");
		
		isLoginNeedVerifyCode = new Combo(shell, SWT.NONE);
		isLoginNeedVerifyCode.setItems(new String[] {"登录", "不登录"});
		
		isLoginNeedVerifyCode.setData("登录","true");
		isLoginNeedVerifyCode.setData("不登录","false");
		
		count = isLoginNeedVerifyCode.getItemCount();
		
		for(int i = 0; i < count; i++){
			if(isLoginNeedVerifyCode.getData(isLoginNeedVerifyCode.getItem(i)).toString().equals(Constant.IS_LOGIN_NEED_VERIFYCODE)){
				isLoginNeedVerifyCode.select(i);
				break;
			}
		}
		
		isLoginNeedVerifyCode.setBounds(217, 41, 86, 25);
		
		Label lblNewLabel_1 = new Label(shell, SWT.NONE);
		lblNewLabel_1.setBackground(SWTResourceManager.getColor(173, 216, 230));
		lblNewLabel_1.setBounds(309, 41, 125, 25);
		lblNewLabel_1.setText("需要验证码时是否登录");
		
		sameTimeLogin = new Text(shell, SWT.BORDER);
		sameTimeLogin.setBounds(217, 10, 86, 25);
		sameTimeLogin.setText(Constant.SAME_TIME_LOGIN);
		
		Label lblNewLabel = new Label(shell, SWT.NONE);
		lblNewLabel.setBackground(SWTResourceManager.getColor(173, 216, 230));
		lblNewLabel.setBounds(309, 10, 125, 25);
		lblNewLabel.setText("同时登录个数");
		
		loginTime = new Text(shell, SWT.BORDER);
		loginTime.setBounds(217, 72, 86, 25);
		loginTime.setText(Constant.LOGIN_TIME);
		
		Label lblNewLabel_2 = new Label(shell, SWT.NONE);
		lblNewLabel_2.setBackground(SWTResourceManager.getColor(173, 216, 230));
		lblNewLabel_2.setBounds(309, 72, 125, 25);
		lblNewLabel_2.setText("持续登录时间（分钟）");
		
		autoShutdown = new Button(shell, SWT.CHECK);
		autoShutdown.setBackground(SWTResourceManager.getColor(173, 216, 230));
		autoShutdown.setBounds(217, 106, 98, 17);
		autoShutdown.setText("挂完自动关机");
		
		autoShutdown.setSelection(Constant.AUTO_SHUTDOWN);
		
		autoRun = new Button(shell, SWT.CHECK);
		autoRun.setBackground(SWTResourceManager.getColor(173, 216, 230));
		autoRun.setBounds(10, 134, 98, 17);
		autoRun.setText("开机启动");
		autoRun.setSelection(Constant.AUTO_RUN);
		
		autoLogin = new Button(shell, SWT.CHECK);
		autoLogin.setBackground(SWTResourceManager.getColor(173, 216, 230));
		autoLogin.setBounds(217, 134, 217, 17);
		autoLogin.setText("启动后自动登录");
		autoLogin.setSelection(Constant.AUTO_LOGIN);
		
		seize = new Button(shell, SWT.CHECK);
		seize.setBackground(SWTResourceManager.getColor(173, 216, 230));
		seize.setBounds(10, 157, 98, 17);
		seize.setText("是否自动抢线");
		seize.setSelection(Constant.SEIZE);
		
		timingLogin = new Button(shell, SWT.CHECK);
		timingLogin.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if(timingLogin.getSelection()){
					alert("选择定时登录后，软件将会在您指定的时间登录列表中的QQ号码，请确保列表中的QQ号码都可以免码登录，并且会取消挂完自动关机功能！");
					autoShutdown.setSelection(false);
					hour.setEnabled(true);
					minute.setEnabled(true);
				} else {
					hour.setEnabled(false);
					minute.setEnabled(false);
				}
			}
		});
		
		timingLogin.setBackground(SWTResourceManager.getColor(173, 216, 230));
		timingLogin.setBounds(217, 157, 98, 17);
		timingLogin.setText("定时登录");
		
		timingLogin.setSelection(Constant.TIMING_LOGIN);
		
		hour = new Combo(shell, SWT.NONE);
		hour.setBounds(10, 180, 45, 25);
		
		String[] hours = new String[24];
		
		for(int i = 0; i < 24; i++){
			hours[i] = Integer.toString(i);
		}
		
		hour.setItems(hours);
		hour.select(Integer.parseInt(Constant.HOUR));
		
		if(timingLogin.getSelection()){
			hour.setEnabled(true);
		} else {
			hour.setEnabled(false);
		}
		
		hourLabel = new Label(shell, SWT.NONE);
		hourLabel.setBackground(SWTResourceManager.getColor(173, 216, 230));
		hourLabel.setBounds(61, 183, 32, 17);
		hourLabel.setText("时");
		
		minute = new Combo(shell, SWT.NONE);
		minute.setBounds(102, 180, 45, 25);
		
		String[] minutes = new String[60];
		
		for(int i = 0; i < 60; i++){
			minutes[i] = Integer.toString(i);
		}
		
		minute.setItems(minutes);
		minute.select(Integer.parseInt(Constant.MINUTE));
		
		if(timingLogin.getSelection()){
			minute.setEnabled(true);
		} else {
			minute.setEnabled(false);
		}
		
		minuteLabel = new Label(shell, SWT.NONE);
		minuteLabel.setBackground(SWTResourceManager.getColor(173, 216, 230));
		minuteLabel.setBounds(153, 183, 32, 17);
		minuteLabel.setText("分");
	}
	
	/**
	 * 
	 * 方法概述：提示信息对话框
	 * 描述：提示信息对话框
	 * @param info
	 * 返回类型：void
	 * 修改人：梁铭显
	 * 修改时间：2012-9-8
	 */
	public void alert(String info){
		 MessageBox dialog=new MessageBox(shell,SWT.OK|SWT.ICON_INFORMATION);
	     dialog.setText("提示");
	     dialog.setMessage(info);
	     dialog.open();
	}
}
